package cn.bocweb.spinning.view.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.CollectListBean;
import cn.bocweb.spinning.model.Bean.CollectRemoveBean;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.LibListBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.MyTestCollectAdapter;
import cn.bocweb.spinning.view.adapter.TestListAdapter;
import cn.bocweb.spinning.view.adapter.TrainAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.ZoomOutPageTransformer;
import cn.bocweb.spinning.view.fragment.MyTestCollectFragment;
import de.greenrobot.event.EventBus;

public class MyTestCollectActivity extends BaseActivity implements View.OnClickListener {
    TrainAdapter trainAdapter;

    List<MyTestCollectFragment> fragments;
    MyTestCollectAdapter myTestCollectAdapter;
    TestListAdapter testListAdapter;
    int size, popupwindowClickPosition;
    Map<Integer, Boolean> answerMap;
    TextView examPopupRight;
    TextView examPopupWrong;
    TextView examPopupMiss;
    TextView examPopupMore;
    PopupWindow popupWindow;
    Map<Integer, Integer> trainType;
    UserPresenter presenter;
    String userid, libid;
    int page = 1, quizCount = 0;
    boolean isRemove = false;
    @Bind(R.id.my_test_collect_detail)
    LinearLayout myTestCollectDetail;
    @Bind(R.id.my_test_collect_num)
    TextView myTestCollectNum;
    @Bind(R.id.my_test_collect_count)
    TextView myTestCollectCount;
    @Bind(R.id.my_test_collect_list)
    LinearLayout myTestCollectList;
    @Bind(R.id.my_test_collect_delete)
    LinearLayout myTestCollectDelete;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.my_test_collect_viewpager)
    ViewPager myTestCollectViewpager;
    int delectPosition;
    @Bind(R.id.linearLayout_empty)
    LinearLayout linearLayoutEmpty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_test_collect);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        fragments = new ArrayList<>();
        initModel();
        initToolbar();
        initClickBtn();
        initViewPager();
        initPopupWindow();
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    private void initToolbar() {
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MyTestCollectActivity.this);
                builder.setTitle("温馨提示");
                builder.setMessage("是否退出答题");
                builder.setPositiveButton("继续答题", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("退出答题", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();

                    }
                });
                builder.show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MyTestCollectActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("是否退出答题");
        builder.setPositiveButton("继续答题", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("退出答题", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();

            }
        });
        builder.show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
        DeviceUtil.Log("onStop");
    }

    public void onEventMainThread(CollectListBean bean) {

        if (bean.getReturn_code() == 0) {
            myTestCollectViewpager.setVisibility(View.VISIBLE);
            linearLayoutEmpty.setVisibility(View.GONE);
            if (!isRemove) {
                quizCount = bean.getTotal();
                for (int i = 0; i < bean.getTotal(); i++) {
                    fragments.add(new MyTestCollectFragment(i, userid, libid));
//                    switch (Integer.parseInt(bean.getData().get(i).getIsright())) {
//                        case 0: {
//                            answerMap.put(i, false);
//                            break;
//                        }
//                        case 1: {
//                            answerMap.put(i, true);
//                            break;
//                        }
//                        case 2: {
//                            break;
//                        }
//                    }
                }
                myTestCollectNum.setText(String.valueOf(myTestCollectViewpager.getCurrentItem() + 1));
                myTestCollectAdapter.notifyDataSetChanged();
                myTestCollectCount.setText(String.valueOf(quizCount));
                testListAdapter.setSize(bean.getTotal());
                testListAdapter.notifyDataSetChanged();
            } else {
                fragments.clear();
                myTestCollectAdapter.notifyDataSetChanged();
                for (int i = 0; i < bean.getTotal(); i++) {
                    fragments.add(new MyTestCollectFragment(i, userid, libid));
//                    switch (Integer.parseInt(bean.getData().get(i).getIsright())) {
//                        case 0: {
//                            answerMap.put(i, false);
//                            break;
//                        }
//                        case 1: {
//                            answerMap.put(i, true);
//                            break;
//                        }
//                        case 2: {
//                            break;
//                        }
//                    }
                }
                myTestCollectAdapter.notifyDataSetChanged();
                myTestCollectCount.setText(String.valueOf(quizCount));
                testListAdapter.setSize(bean.getTotal());
                testListAdapter.notifyDataSetChanged();
            }
        } else if (bean.getReturn_code() == -204) {
            myTestCollectViewpager.setVisibility(View.GONE);
            linearLayoutEmpty.setVisibility(View.VISIBLE);
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(CollectRemoveBean bean) {

        if (bean.getReturn_code() == 0) {

            quizCount--;

            myTestCollectCount.setText(String.valueOf(quizCount));

            fragments.remove(delectPosition);
            for (int i = 0; i < fragments.size(); i++) {
                fragments.get(i).setPosition(i);
            }
            myTestCollectAdapter.notifyDataSetChanged();
            myTestCollectViewpager.setCurrentItem(0);

            isRemove = true;
            answerMap.remove(delectPosition);
            testListAdapter.setSize(quizCount);
            testListAdapter.notifyDataSetChanged();
            myTestCollectNum.setText(String.valueOf(myTestCollectViewpager.getCurrentItem() + 1));

            if (fragments.size() == 0) {
                myTestCollectViewpager.setVisibility(View.GONE);
                linearLayoutEmpty.setVisibility(View.VISIBLE);
                myTestCollectNum.setText("0");
            }
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }


    public void onEventMainThread(ErrorBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getErrorMsg());
    }


    private void initModel() {
        UserBean.DataEntity user = new UserBean.DataEntity();
        user.readInfoFromLocal(this);
        userid = user.getUserid();

        LibListBean.DataEntity lib = new LibListBean.DataEntity();
        lib.readLibListIntoLocal(this);
        libid = lib.getId();

        presenter = new UserPresenterImp();
        presenter.collectList(libid, userid, "50", page);
    }

    private void initClickBtn() {
        myTestCollectList.setOnClickListener(this);
        myTestCollectDelete.setOnClickListener(this);
        myTestCollectDetail.setOnClickListener(this);
    }

    private void initPopupWindow() {

        answerMap = new HashMap<>();

        View view = LayoutInflater.from(this).inflate(R.layout.window_test_list, null);
        GridView gridView_testList = (GridView) view.findViewById(R.id.test_list);
        RelativeLayout iv = (RelativeLayout) view.findViewById(R.id.btn_hide);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        testListAdapter = new TestListAdapter(this, size, answerMap, false);

        examPopupRight = (TextView) view.findViewById(R.id.exam_popup_right);
        examPopupWrong = (TextView) view.findViewById(R.id.exam_popup_wrong);
        examPopupMiss = (TextView) view.findViewById(R.id.exam_popup_miss);
        examPopupMore = (TextView) view.findViewById(R.id.exam_popup_more);
        examPopupMore.setVisibility(View.VISIBLE);
        examPopupMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page++;
                presenter.collectList(libid, userid, "50", page);
            }
        });

        gridView_testList.setAdapter(testListAdapter);

        int screenHeightPx = DeviceUtil.getScreenHeight(this);
        int navigationHeight = DeviceUtil.getStatusBarHeight(this);
        final int toolbarHeight = DeviceUtil.getViewHeight(toolbar);
        /**
         * 安卓5.0以下有个问题就是用gridview的onItemClickListener监听不到item的监听事件.真他妈的奇怪
         */
        testListAdapter.setOnItemClickListener(new TestListAdapter.OnItemClickListener() {
            @Override
            public void click(int position) {
                myTestCollectViewpager.setCurrentItem(position);
                popupWindow.dismiss();
            }
        });
        popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, screenHeightPx - navigationHeight - toolbarHeight);
        popupWindow.setAnimationStyle(R.style.test_list);

    }

    private void initViewPager() {
        myTestCollectAdapter = new MyTestCollectAdapter(getSupportFragmentManager(), fragments);
        myTestCollectViewpager.setAdapter(myTestCollectAdapter);
        myTestCollectViewpager.setPageTransformer(true, new ZoomOutPageTransformer());
        myTestCollectViewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                myTestCollectNum.setText(String.valueOf(position + 1));
//                presenter.collectQuestion(position, userid, libid);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void setAnswerMap(int position, boolean isRight) {
        answerMap.put(position, isRight);
        testListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_test_collect_list: {
                if (fragments.isEmpty()) {
                    DeviceUtil.MyToast(MyTestCollectActivity.this, "当前无收藏题");
                    break;
                }
                testListAdapter.notifyDataSetChanged();
                popupWindow.showAtLocation(myTestCollectDetail, Gravity.BOTTOM, 0, 0);
                break;
            }
            case R.id.my_test_collect_delete: {
                if (fragments.isEmpty()) {
                    DeviceUtil.MyToast(MyTestCollectActivity.this, "当前无收藏题");
                    break;
                }
                DeviceUtil.Log("id = " + fragments.get(myTestCollectViewpager.getCurrentItem()).getId() + " ttype = " + fragments.get(myTestCollectViewpager.getCurrentItem()).getTtype());
                presenter.collectRemove(libid, userid, "2", fragments.get(myTestCollectViewpager.getCurrentItem()).getTid(), fragments.get(myTestCollectViewpager.getCurrentItem()).getTtype());
                delectPosition = myTestCollectViewpager.getCurrentItem();
                break;
            }
            case R.id.my_test_collect_detail: {
                if (fragments.size() > 0) {
                    fragments.get(myTestCollectViewpager.getCurrentItem()).showExplain();
                }
                break;
            }
        }
    }
}
